<script setup lang="ts">
// @ts-nocheck
import { computed, ref, h, onMounted } from 'vue';
import { getConsignmentList, addConsignment, updateConsignment, deleteConsignment, uploadFile } from '#/api'
import {
  Button,
  Card,
  Form,
  Input,
  InputNumber,
  Modal,
  Table,
  Upload,
  message,
} from 'ant-design-vue';

// 仅用于避免 lint 误判"导入未使用"（模板中已使用这些组件）
// 这行不会影响运行时逻辑
void [Button, Card, Form, Input, InputNumber, Modal, Table, Upload];

interface Consignment {
  id: number;
  item: string;
  description: string;
  price: number;
  phone: string;
}

// 个人寄售数据
const consignments = ref<Consignment[]>([]);
const searchName = ref('');

// 前端过滤
const filteredList = computed(() =>
  consignments.value.filter(c => !searchName.value || c.name.toLowerCase().includes(searchName.value.toLowerCase()))
);

// 表格列定义
const columns = [
  { title: '商品', dataIndex: 'name', key: 'name' },
  { title: '商品描述', dataIndex: 'description', key: 'description' },
  { title: '价格(元)', dataIndex: 'price', key: 'price' },
  { title: '联系人电话', dataIndex: 'contactTel', key: 'contactTel' },
  {
    title: '商品图片',
    key: 'image',
    customRender: ({ record }: any) =>
      h('div', { class: 'flex gap-2' },
        (record.image || []).slice(0, 3).map((url: string) =>
          h('img', { src: url, class: 'w-16 h-16 object-cover rounded', onClick: () => window.open(url) })
        )
      ),
  },
  {
    title: '操作',
    key: 'action',
    customRender: ({ record }: any) =>
      h('div', [
        h(
          Button,
          { 
            type: 'link',
            onClick: () => handleEdit(record)
          },
          { default: () => '编辑' },
        ),
        h(
          Button,
          { 
            type: 'link', 
            danger: true,
            onClick: () => handleDelete(record)
          },
          { default: () => '删除' },
        ),
      ]),
  },
];

// 商品弹窗（新增/编辑共用）
const showModal = ref(false);
const saving = ref(false);
const isEdit = ref(false);
const modalTitle = computed(() => isEdit.value ? '编辑寄售' : '新增寄售');
const currentEditId = ref<number | null>(null);

const addForm = ref({
  name: '',
  description: '',
  price: null as number | null,
  contactTel: '',
  image: [] as string[],
});

// 上传文件列表
const fileList = ref<any[]>([]);

function resetAddForm() {
  addForm.value = {
    name: '',
    description: '',
    price: null,
    contactTel: '',
    image: [],
  };
  fileList.value = [];
}

function handleRemove() {
  fileList.value = [];
}

function handleCancel() {
  showModal.value = false;
  resetAddForm();
  isEdit.value = false;
  currentEditId.value = null;
}

// 编辑寄售
function handleEdit(record: Consignment) {
  isEdit.value = true;
  currentEditId.value = record.id;
  addForm.value = {
    name: record.name,
    description: record.description,
    price: record.price,
    contactTel: record.contactTel,
    image: record.image || [],
  };
  // 回显已有图片
  fileList.value = (record.image || []).map((url: string, idx: number) => ({ uid: idx, url, status: 'done' }));
  showModal.value = true;
}

// 删除寄售
async function handleDelete(record: Consignment) {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除"${record.name}"寄售吗？`,
    okText: '确认',
    cancelText: '取消',
    async onOk() {
      try {
        await deleteConsignment(record.id);
        message.success('删除成功');
        // 重新拉最新列表
        const res = await getConsignmentList();
        consignments.value = Array.isArray(res) ? res : (res?.data || []);
      } catch {
        message.error('删除失败');
      }
    }
  });
}

// 初始加载
onMounted(async () => {
  try {
    const res = await getConsignmentList();
    const list = Array.isArray(res) ? res : (res?.data || []);
    consignments.value = list;
  } catch {
    message.error('获取寄售列表失败');
  }
});

// 校验规则（antd Form 用）
const rules = {
  name: [{ required: true, message: '请输入商品名称' }],
  description: [{ required: true, message: '请输入商品描述' }],
  price: [
    { required: true, message: '请输入价格' },
    {
      validator: (_: any, value: number) => {
        if (value == null || value < 0) return Promise.reject('请输入有效的价格');
        return Promise.resolve();
      },
    },
  ],
  contactTel: [
    { required: true, message: '请输入联系人电话' },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: '请输入正确的手机号码',
    },
  ],
};

const canSubmit = computed(() =>
  !!addForm.value.name && 
  !!addForm.value.description && 
  addForm.value.price != null && 
  addForm.value.price >= 0 &&
  !!addForm.value.contactTel
);

// 上传
async function handleUpload({ file, onSuccess, onError }: any) {
  try {
    const res = await uploadFile(file);
    onSuccess(res?.message || '');
  } catch {
    onError(new Error('上传失败'));
  }
}

async function handleSubmit() {
  if (!canSubmit.value) {
    message.error('请完善表单信息');
    return;
  }
  saving.value = true;
  
  const payload = {
    name: addForm.value.name.trim(),
    description: addForm.value.description.trim(),
    price: Number(addForm.value.price || 0),
    contactTel: addForm.value.contactTel.trim(),
    image: fileList.value.map((f: any) => f.response || f.url || ''),
  };
  
  try {
    if (isEdit.value && currentEditId.value !== null) {
      // 编辑：调真实接口
      await updateConsignment({ ...payload, id: currentEditId.value });
      message.success('编辑寄售成功');
    } else {
      // 新增：调真实接口
      await addConsignment(payload);
      message.success('新增寄售成功');
    }
    // 重新拉最新列表
    const res = await getConsignmentList();
    consignments.value = Array.isArray(res) ? res : (res?.data || []);
    showModal.value = false;
    resetAddForm();
    isEdit.value = false;
    currentEditId.value = null;
  } catch {
    message.error('保存失败');
  } finally {
    saving.value = false;
  }
}
</script>

<template>
  <div class="p-4">
    <Card>
      <template #title>
        个人寄售管理
      </template>
      <template #extra>
        <Button type="primary" @click="showModal = true; isEdit = false; resetAddForm();">新增寄售</Button>
      </template>
      <!-- <div class="text-gray-500 mb-4">展示个人寄售商品清单，支持录入、修改、删除、上架、下架等。</div> -->
      <!-- 顶部搜索 -->
      <div class="mb-4 flex gap-3">
        <Input v-model:value="searchName" placeholder="请输入商品名称" style="width: 240px" />
        <Button @click="searchName = ''">重置</Button>
      </div>
      <Table :columns="columns" :dataSource="filteredList" :pagination="false" :rowKey="r => r.id" />
    </Card>

    <!-- 寄售弹窗（新增/编辑共用） -->
    <Modal
      v-model:open="showModal"
      :confirmLoading="saving"
      :title="modalTitle"
      @ok="handleSubmit"
      @cancel="handleCancel"
      destroyOnClose
      width="600px"
    >
      <Form :model="addForm" :rules="rules" layout="horizontal" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
        <Form.Item name="name" label="商品名称" :rules="rules.name">
          <Input v-model:value="addForm.name" placeholder="请输入商品名称" />
        </Form.Item>
        <Form.Item name="description" label="商品描述" :rules="rules.description">
          <Input v-model:value="addForm.description" placeholder="请输入商品描述" />
        </Form.Item>
        <Form.Item name="price" label="价格(元)" :rules="rules.price">
          <InputNumber v-model:value="addForm.price" :min="0" :precision="2" style="width: 100%" placeholder="请输入价格" />
        </Form.Item>
        <Form.Item name="contactTel" label="联系人电话" :rules="rules.contactTel">
          <Input v-model:value="addForm.contactTel" placeholder="请输入联系人电话" />
        </Form.Item>
        <Form.Item label="商品图片">
          <Upload
            v-model:fileList="fileList"
            list-type="picture-card"
            :customRequest="handleUpload"
            :remove="handleRemove"
          >
            <div>选择图片</div>
          </Upload>
        </Form.Item>
      </Form>
    </Modal>
  </div>
</template>